package service

import (
	"gorm.io/gorm"
	"time"
	"view-crawler-backend/internal/biz_error"
	"view-crawler-backend/internal/dao"
	"view-crawler-backend/internal/dao/entity"
	"view-crawler-backend/internal/tools"
)

func QueryAllCategories() ([]entity.Category, error) {
	return dao.QueryAllCategories(dao.DB)
}

func UpdateCategory(newAddCategoryList []string, newDelCategoryList []int64) ([]int64, error) {
	// 检查要删除的类别是否已经被使用
	if len(newDelCategoryList) > 0 {
		isInUse, err := dao.IsCategoriesInUse(dao.DB, newDelCategoryList)
		if err != nil {
			return nil, err
		}
		if isInUse {
			return nil, biz_error.CategoryDelError
		}
	}

	// 为新增类别生成ID
	categoryIdList := make([]int64, len(newAddCategoryList))
	for i := range newAddCategoryList {
		categoryIdList[i] = tools.GenerateId()
		time.Sleep(time.Millisecond * 2)
	}
	// 构建Category实体列表
	categoryList := make([]entity.Category, len(newAddCategoryList))
	for i := range categoryList {
		categoryList[i] = entity.Category{
			CategoryId:   categoryIdList[i],
			CategoryName: newAddCategoryList[i],
		}
	}
	// 执行更新
	if err := dao.DB.Transaction(func(tx *gorm.DB) error {
		// 删除类别
		if len(newDelCategoryList) > 0 {
			if err := dao.DeleteCategoryByIdList(tx, newDelCategoryList); err != nil {
				return err
			}
		}
		if len(newAddCategoryList) > 0 {
			// 新建类别
			if err := dao.BatchAddCategory(tx, categoryList); err != nil {
				return err
			}
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return categoryIdList, nil
}
